
import requests as r
import codecs
import os
from bs4 import BeautifulSoup

# bytearray() converts a string to bytearray , then you can write that bytearray to file


headers = {
	"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
	# "Host":"www.ximalaya.com",
	"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
	'Range':'bytes=0-90000000'
}



# resp = r.get("http://www.ximalaya.com/44322173/album/3866917/?feed=reset",headers = headers)
resp = r.get("http://www.ximalaya.com/44322173/album/3866836/",headers = headers)

albumname = "album1"
if not os.path.exists(albumname):
	os.mkdir(albumname)

soup = BeautifulSoup(resp.text , 'html.parser')
res = soup.select(".personal_body")

sound_ids = res[0]["sound_ids"]
sound_ids = sound_ids.split(",")

for id in sound_ids:

	resp = r.get("http://www.ximalaya.com/tracks/" + str(id) + ".json",headers=headers);
	title = resp.json()['title']
	path = resp.json()['play_path_32']

	mus_resp = r.get(path,headers=headers, stream=True)

	with open( albumname + "/" +title + ".m4a", 'wb') as fd:
	    for chunk in mus_resp.iter_content(chunk_size=128):
	        fd.write(chunk)

exit()


print soup.prettify()

with codecs.open("tmp","w","utf-8") as tmp:
	# print tmp.encoding
	tmp.write(str)


resp = r.get("http://www.ximalaya.com/tracks/13147361.json",headers=headers);
print resp.json()['play_path_32']



# headers['Range'] = 'bytes=0-90000000'

# print os.path.getsize('1233')

# mus_resp = r.get("http://audio.xmcdn.com/group7/M07/21/73/wKgDWlbmOa3TD0D_AArDQp_Mj5Y641.m4a",headers=headers, stream=True)
# print len(mus_resp.content)

# print len(mus_resp.content)
# fd = open( "1233", 'wb') 
# fd.write(mus_resp.content)
# fd.flush()
# fd.close()
# print os.path.getsize('1233')

# with open( "1233", 'wb') as fd:
# 	    for chunk in mus_resp.iter_content(chunk_size=128):
# 	        fd.write(chunk)

# f.write(barr)
# print type(str)

# str.decode("ascii","ignore")
# f = open("tmp","w")
# barr = bytearray(str,"utf-8")
# barr = barr.decode("iso-8859-1")
